package com.example.utils;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.base.domain.TableDataInfo;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collection;

/**
 * 乱七八糟的转换类
 * @author wanghongyu02
 * @date 2024-08-09 16:19
 */
public class CvtUtils {

    /**
     * 将IPage转换为TableDataInfo
     * @author wanghongyu02
     * @date 2024-08-09 16:24
     * @param ipage
     * @return com.example.base.domain.TableDataInfo
     */
    public static TableDataInfo cvtIPageToTableDataInfo(IPage ipage) {

        TableDataInfo tableDataInfo = new TableDataInfo();

        tableDataInfo.setCode(200);

        if (CollectionUtils.isEmpty(ipage.getRecords())) {
            tableDataInfo.setRows(new ArrayList<>());
            tableDataInfo.setMsg("查询成功,数据记录为空");
        } else {
            tableDataInfo.setRows(ipage.getRecords());
            tableDataInfo.setTotal(ipage.getTotal());
            tableDataInfo.setMsg("查询成功");
        }

        return tableDataInfo;
    }

    // 将 snake_case 转换为 camelCase 的方法
    public static String toCamelCase(String snakeCase) {
        String[] parts = snakeCase.split("_");
        StringBuilder camelCase = new StringBuilder(parts[0].toLowerCase());
        for (int i = 1; i < parts.length; i++) {
            camelCase.append(parts[i].substring(0, 1).toUpperCase()).append(parts[i].substring(1).toLowerCase());
        }
        return camelCase.toString();
    }

    // 转换 JSONObject 的所有 key，包括嵌套的子 JSONObject
    public static JSONObject convertSnakeToCamelKeys(JSONObject jsonObject) {
        JSONObject newJsonObject = new JSONObject();

        for (String key : jsonObject.keySet()) {
            String camelCaseKey = toCamelCase(key);

            Object value = jsonObject.get(key);

            if (value instanceof JSONObject) {
                newJsonObject.put(camelCaseKey, convertSnakeToCamelKeys((JSONObject) value));
            } else {
                newJsonObject.put(camelCaseKey, value);
            }
        }
        return newJsonObject;
    }

}
